package com.kdg.thread.consurrenttest.threadpool;

import java.util.concurrent.*;

/**
 * 线程池扩展
 * @author kdg
 * @description:
 * @date 2018/5/15.
 */
public class ThreadPoolsExtend {

    private static final int COOL_POOL_SIZE = 10;
    public static class MyTask implements Runnable{
        private String name;

        public MyTask() {
        }

        public MyTask(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println("正在执行：Thread ID:"+Thread.currentThread().getId()+", Task name is "+name);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //线程池的几个回调方法
        /*ExecutorService es = new ThreadPoolExecutor(5,5,0L,
                TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()){
            @Override
            protected void beforeExecute(Thread t, Runnable r) {
                System.out.println("准备执行之前"+((MyTask)r).name);
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                System.out.println("执行完成之后"+((MyTask)r).name);
            }

            @Override
            protected void terminated() {
                System.out.println("线程池退出");
            }
        };
        for(int i=0;i<5;i++){
            Thread.sleep(1000);
            es.execute(new MyTask("Thread"+i));
        }
        es.shutdown();*/
        //2.线程池ThreadPoolExecutor完整参数：
        ExecutorService es2 = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,
                new SynchronousQueue<Runnable>(),
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        System.out.println(r.toString()+" is discard");
                    }
                });
        MyTask myTask = new MyTask();
        for(int i=0;i<Integer.MAX_VALUE;i++){
            es2.submit(myTask);
            Thread.sleep(10);
        }
    }
}
